import React from 'react'
import { Select, success, CropImageUpload,DateSelect,Tooltip, error, info, Link, Toast, Input, Checkbox } from '../ui-components'
import { Button } from 'sq-ui';
import style from './style'
import { connect } from 'react-redux'
import timezones from '../constants/zones'
import util from '../util'
import cx from 'classnames'
import {FieldContainer, FieldBox} from '../ui-components/form'
import moment from 'moment'
import validate from '../libs/test'
import { findDOMNode } from 'react-dom'

class NewAccount extends React.Component {

  init = {
    orgFullName: '',
    orgShortName: '',
    orgAvatarUrl: '',
    orgTimeZone: 8,
    onboardingRequestVO: {
      emailAddress: '',
      mobilePhone: '',
      fullName: '',
      //citizenId: ''
      //gender: 0,
      //enrollDate: null,
      //contractType: 1,
      //employmentStatus: 1,
    },
    sqStaffMobilePhone: '',
    smsVerificationCode: ''
  }

  initCount = 60

  state = {
    step: 1,
    count: this.initCount,
    sending: false,
    fields: this.init
  }

  handleSendSms() {
    if (this.props.validate(['sqStaffMobilePhone'], { value: this.state.fields.sqStaffMobilePhone, el: this.refs.sendSmsButton })) return
    this.count()
    this.props.sendSms(this.state.fields.sqStaffMobilePhone, () => {
      this.setState({
        sending: true
      })
    })
  }

  handleSave() {
    const { fields } = this.state
    const { onboardingRequestVO } = fields
    if (Object.keys(fields).some(key => !fields[key] && key!=='orgAvatarUrl' && fields[key] !== 0 )  || 
      Object.keys(onboardingRequestVO).some(key => !onboardingRequestVO[key] && onboardingRequestVO[key] !== 0 ) ) {
      return error('请填写完整!')
    }
    this.props.saveOrgAccount(this.state.fields, () => {
      success('开户成功！请去邮箱查看确认邮件.')
      this.setState({
        step: 2
      })
    })
  }

  count() {
    this.interval = setInterval(() => {
      if (this.state.count === 1) {
        clearInterval(this.interval)
        this.setState({
          count: this.initCount,
          sending: false
        })
        return
      }
      this.setState({
        count: this.state.count - 1
      })
    }, 1000)
  }

  updateField(name, e) {
    const { value } = e.target
    if (/^\s+$/.exec(value)) return
    const [ name_1, name_2 ] = name.split(':')
    if (!name_2) {
      this.setState({
        fields: {
          ...this.state.fields,
          [name]: e.target.value
        }
      })
    } else {
      this.setState({
        fields: {
          ...this.state.fields,
          [name_1]: {
            ...this.state.fields[name_1],
            [name_2]: e.target.value
          }
        }
      })
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval)
  }

  renderItem(v, i) {
    const [ label, name ] = v.split('|')
    const [ name_1, name_2 ] = name.split(':')
    let value
    if (name_2) {
      value = this.state.fields[name_1][name_2]
    } else {
      value = this.state.fields[name]
    }
    const input = (
      <div 
        key={i}
        className={style.input}
      >
        <input 
          type="text" 
          placeholder={label} 
          ref={name_2 || name} 
          onChange={e => this.updateField(name, e)} 
          value={value} 
        />
      </div>
    )
    if (name === 'sqStaffMobilePhone') {
      return (
        <div 
          key={i} 
          className={cx(style['send-sms'], style.input)}
        >
          { input }
          <button 
            style={{ fontSize: '12px' }}
            ref="sendSmsButton"
            className={style['send-sms-button']}
            onClick={::this.handleSendSms}
            disabled={ !this.state.fields.sqStaffMobilePhone || this.state.sending}
            >{ this.state.sending? (this.state.count+'s后重新发送'): "点击发送验证码"}</button>
        </div>
      )
    }
    return input
  }

	render() {
    const { footer } = this.props
    const { step, fields } = this.state
    const { onboardingRequestVO } = fields
    if (step == 2) {
      return (
        <div className={style['after-new-account']}>
          <h2>恭喜，开户成功</h2>
          <ul>
            <li>请前往管理员邮箱查收邮件，了解后续步骤。</li>
          </ul>
        </div>
      )
    }
    return (
      <div>
        <h1 className={style.title}>企业开户</h1>
        <div>
          <div className={style.form}>
            <h3 className={style.title}>设置基本信息</h3>
            {
              [
                '公司名称|orgFullName', 
                '公司简称|orgShortName'
              ].map(::this.renderItem)
            }
            <CropImageUpload
              width="80"
              className={style['upload-logo']}
              placeholder="点击上传公司logo"
              file={fields.orgAvatarUrl}
              onUpload={({ x, y, e, file }) => {
                this.props.updateOnboardingAvatar({
                  x, y, e
                }, ({ presignedPutUrl, publicGetUrl }) => {
                  this.props.fileUpload({
                    url: presignedPutUrl,
                    file: file.file,
                    cb: () => {
                      this.setState({
                        fields: {
                          ...this.state.fields,
                          orgAvatarUrl: publicGetUrl
                        }
                      })
                    }
                  })
                })
              }}
            />
          </div>
          <div className={style.form}>
            <h3 className={style.title}>设置管理员帐号</h3>
            {
              [
                '企业邮箱|onboardingRequestVO:emailAddress', 
                '手机号|onboardingRequestVO:mobilePhone', 
                '姓名|onboardingRequestVO:fullName', 
              ].map(::this.renderItem)
            }
          </div>
          <div className={style.form}>
            <h3 className={style.title}>开户验证</h3>
            {
              [
                '信任手机号（「Better OKR」工作人员提供）|sqStaffMobilePhone', 
                '验证码|smsVerificationCode'
              ].map(::this.renderItem)
            }
            <Button blue className={style.button} onClick={::this.handleSave} label="立即开户" />
          </div>
        </div>
      </div>
    )
	}
}

export default NewAccount
